package com.neusoft.elm.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.neusoft.elm.po.User;
import com.neusoft.elm.service.UserService;
import com.neusoft.elm.service.impl.UserServiceImpl;

/**
 * 用户注册Servlet
 * 对应原UserController的saveUser方法
 */
@WebServlet("/UserController/saveUser")
public class UserRegisterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 设置编码和响应类型
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        
        // 添加CORS支持
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
        
        PrintWriter out = response.getWriter();
        ObjectMapper om = new ObjectMapper();
        
        try {
            String userId = request.getParameter("userId");
            String password = request.getParameter("password");
            String userName = request.getParameter("userName");
            Integer userSex = Integer.parseInt(request.getParameter("userSex"));
            
            System.out.println("接收到注册请求：userId=" + userId + ", userName=" + userName + ", userSex=" + userSex);
            
            User user = new User(userId, password, userName, userSex, null);
            UserService service = new UserServiceImpl();
            int result = service.saveUser(user);
            
            System.out.println("注册服务返回结果: " + result);
            
            // 处理不同的返回结果
            if (result == -1) {
                // 用户ID已存在
                System.out.println("用户ID重复，返回错误信息");
                response.setStatus(HttpServletResponse.SC_CONFLICT);
                out.print("{\"error\":\"用户ID已存在，请使用其他手机号注册\",\"code\":-1}");
            } else if (result > 0) {
                // 注册成功
                System.out.println("注册成功，返回成功信息");
                out.print("{\"message\":\"注册成功\",\"code\":1}");
            } else {
                // 注册失败
                System.out.println("注册失败，result=" + result);
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                out.print("{\"error\":\"注册失败，请稍后重试\",\"code\":0}");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.print("{\"error\":\"服务器内部错误：" + e.getMessage() + "\"}");
        } finally {
            out.close();
        }
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        doPost(request, response);
    }
    
    @Override
    protected void doOptions(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 处理预检请求
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setStatus(HttpServletResponse.SC_OK);
    }
}